package alfred.mdp.tsp.worker;

import alfred.mdp.messages.ProtocolMessage;
import alfred.mdp.tsp.Titanic;
import alfred.mdp.worker.WorkerService;
import alfred.storage.Storage;
import org.zeromq.ZFrame;
import org.zeromq.ZMsg;

/**
 */
public class ReplyWorker extends WorkerService {
    private final Storage<ZFrame, ZMsg> storage;

    public ReplyWorker(Storage storage) {
        this.storage = storage;
    }

    @Override
    public ZMsg process(ZMsg input) {
        ZFrame uuid = ProtocolMessage.get(input, 0);
        ZMsg data = storage.get(uuid);
        ZMsg result = new ZMsg();
        if (data == null) {
            result.addLast(Titanic.ResponseCode.UNKNOWN);

        } else if (ProtocolMessage.get(data, 0).equals(Titanic.ResponseCode.PENDING)) {
            result.addLast(Titanic.ResponseCode.PENDING);

        } else if (ProtocolMessage.get(data, 0).equals(Titanic.ResponseCode.OK)) {
            return data;

        } else {
            result.addLast(Titanic.ResponseCode.ERROR);
        }
        return result;
    }

    @Override
    public String getName() {
        return Titanic.TITANIC_REPLY_SERVICE;
    }
}
